package city.spring.modules.material.service.impl;

import city.spring.modules.material.entity.MaterialBreakageDeliveryEntity;
import city.spring.modules.material.entity.MaterialBreakageDeliveryMaterialEntity;
import city.spring.modules.material.entity.MaterialQuantityEntity;
import city.spring.modules.material.repository.MaterialBreakageDeliveryMaterialRepository;
import city.spring.modules.material.repository.MaterialBreakageDeliveryRepository;
import city.spring.modules.material.service.MaterialBreakageDeliveryService;
import city.spring.modules.material.service.MaterialQuantityService;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.service.UserService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

import static city.spring.utils.UserUtils.getPrincipal;

/**
 * Service：报损出库
 *
 * @author 谢金婷
 * @date 2021-01-20 10:51:40
 */
@CacheConfig(cacheNames = {MaterialBreakageDeliveryServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Exception.class)
@Service
public class MaterialBreakageDeliveryServiceImpl extends ServiceImpl<MaterialBreakageDeliveryRepository, MaterialBreakageDeliveryEntity> implements MaterialBreakageDeliveryService {

    private final UserService userService;
    private final MaterialBreakageDeliveryRepository materialBreakageDeliveryRepository;
    private final MaterialBreakageDeliveryMaterialRepository materialBreakageDeliveryMaterialRepository;
    private final MaterialQuantityService materialQuantityService;

    public MaterialBreakageDeliveryServiceImpl(UserService userService, MaterialBreakageDeliveryRepository materialBreakageDeliveryRepository, MaterialBreakageDeliveryMaterialRepository materialBreakageDeliveryMaterialRepository, MaterialQuantityService materialQuantityService) {
        this.userService = userService;
        this.materialBreakageDeliveryRepository = materialBreakageDeliveryRepository;
        this.materialBreakageDeliveryMaterialRepository = materialBreakageDeliveryMaterialRepository;
        this.materialQuantityService = materialQuantityService;
    }

    @Override
    public void saveMaterialBreakageDelivery(MaterialBreakageDeliveryEntity entity) {
        UserEntity userEntity = userService.getUserByIdOrAccount(getPrincipal().getName());
        entity.setReporter(userEntity.getId());
        entity.setStatus("待审核");
        entity.setConfirm("否");
        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }

    @Override
    public void updateMaterialBreakageDelivery(MaterialBreakageDeliveryEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        if (!updateById(entity)) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deleteMaterialBreakageDelivery(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteMaterialBreakageDelivery(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }

    @Override
    public IPage<MaterialBreakageDeliveryEntity> listPage(Page<? extends MaterialBreakageDeliveryEntity> page, Wrapper<? extends MaterialBreakageDeliveryEntity> wrapper) {
        return baseMapper.listPage(page, wrapper);
    }

    @Override
    public void confirmDelivery(String id, MaterialBreakageDeliveryEntity entity) {
        //获取该报损出库的物资
        List<MaterialBreakageDeliveryMaterialEntity> deliveryMaterials = materialBreakageDeliveryMaterialRepository.getDeliveryMaterials(entity.getId());
        // 更新库存
        for (MaterialBreakageDeliveryMaterialEntity deliveryMaterial : deliveryMaterials){
            MaterialQuantityEntity materialQuantityEntity = materialQuantityService.getByMaterialIdAndStorehouseId(deliveryMaterial.getMaterialId(), deliveryMaterial.getStorehouseId());
            BigDecimal deliveryquantity = materialQuantityEntity.getDeliveryquantity() == null ? BigDecimal.ZERO : materialQuantityEntity.getDeliveryquantity();
            BigDecimal unitprice = materialQuantityEntity.getUnitprice() == null ? BigDecimal.ZERO : materialQuantityEntity.getUnitprice();
            BigDecimal quantity = materialQuantityEntity.getQuantity() == null ? BigDecimal.ZERO : materialQuantityEntity.getQuantity();
            materialQuantityEntity.setDeliveryquantity(deliveryquantity.add(deliveryMaterial.getBreakageQuantity()));
            materialQuantityEntity.setQuantity(quantity.add(deliveryMaterial.getBreakageQuantity()));
            materialQuantityEntity.setTotal(unitprice.multiply(materialQuantityEntity.getQuantity()));
            materialQuantityService.lambdaUpdate()
                    .set(MaterialQuantityEntity::getDeliveryquantity,materialQuantityEntity.getDeliveryquantity())
                    .set(MaterialQuantityEntity::getQuantity,materialQuantityEntity.getQuantity())
                    .set(MaterialQuantityEntity::getTotal,materialQuantityEntity.getTotal())
                    .eq(MaterialQuantityEntity::getId,materialQuantityEntity.getId())
                    .update();
        }
        entity.setConfirm("是");
        materialBreakageDeliveryRepository.confirmDelivery(id, entity);
    }
}
